package com.github.shiqiyue.app.modules.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.shiqiyue.app.config.ApplicationConfig;
import com.github.shiqiyue.app.config.file.FilePathEnum;
import com.github.shiqiyue.app.config.file.FileService;
import com.github.shiqiyue.app.modules.sys.entity.FileExport;
import com.github.shiqiyue.app.modules.sys.enums.FileExportStatusEnum;
import com.github.shiqiyue.app.modules.sys.mapper.FileExportMapper;
import com.github.shiqiyue.app.modules.sys.service.IFileExportService;
import com.github.shiqiyue.app.modules.sys.task.FileExportTask;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 文件导出 服务实现类
 * </p>
 *
 * @author wenyao.wu
 * @since 2020-05-20
 */
@Service
public class FileExportServiceImpl extends ServiceImpl<FileExportMapper, FileExport> implements IFileExportService {

    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
            0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(100));

    public static final String FILE_SEPARATOR = "/";

    public static final String DATE_FORMAT = "yyyyMMdd";

    @Autowired
    private ApplicationConfig applicationConfig;

    @Autowired
    private FileService fileService;

    @Override
    public Long createFileExportTask(String fileCode, String fileName, FileExportTask task) {
        FileExport fileExport = new FileExport();
        fileExport.setFileCode(fileCode);
        fileExport.setExportStatus(FileExportStatusEnum.CREATED.getValue());
        fileExport.setFilePath(fileService.generatePath(FilePathEnum.TEMP, fileName));
        this.save(fileExport);

        task.setFilePath(fileExport.getFilePath());
        task.setFileExportId(fileExport.getId());
        task.setFileExportService(this);
        task.setFileService(fileService);
        threadPoolExecutor.execute(task);

        return fileExport.getId();
    }


}
